package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.business.domain.SysUserLoginCompany;
import com.ruoyi.business.domain.bo.SysUserLoginCompanyBo;
import com.ruoyi.business.domain.bo.admin.AdminSysUserLoginCompanyBo;
import com.ruoyi.business.domain.vo.SysUserLoginCompanyVo;
import com.ruoyi.business.mapper.SysUserLoginCompanyMapper;
import com.ruoyi.business.mapper.SysUserMapper;
import com.ruoyi.business.service.ISysUserLoginCompanyService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户登录账号关联
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserLoginCompanyServiceImpl implements ISysUserLoginCompanyService {

    private final SysUserLoginCompanyMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    @Override
    public Boolean insert(SysUserLoginCompany sysUserLoginCompany) {
        return baseMapper.insert(sysUserLoginCompany) > 0;
    }


    /**
     * 查询公司信息
     */
    @Override
    public SysUserLoginCompanyVo queryById(Long driverId) {
        return baseMapper.selectVoById(driverId);
    }

    /**
     * 查询公司信息列表
     */
    @Override
    public TableDataInfo<SysUserLoginCompanyVo> queryPageList(SysUserLoginCompanyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserLoginCompany> lqw = buildQueryWrapper(bo);
        Page<SysUserLoginCompanyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询公司信息列表
     */
    @Override
    public List<SysUserLoginCompanyVo> queryList(SysUserLoginCompanyBo bo) {
        LambdaQueryWrapper<SysUserLoginCompany> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserLoginCompany> buildQueryWrapper(SysUserLoginCompanyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserLoginCompany> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPostId() != null, SysUserLoginCompany::getPostId, bo.getPostId());
        lqw.eq(bo.getRelevanceUserId() != null, SysUserLoginCompany::getRelevanceUserId, bo.getRelevanceUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getTel()), SysUserLoginCompany::getTel, bo.getTel());
        lqw.eq(StringUtils.isNotBlank(bo.getElseParams()), SysUserLoginCompany::getElseParams, bo.getElseParams());
        lqw.eq(bo.getDeptId() != null, SysUserLoginCompany::getDeptId, bo.getDeptId());
        lqw.eq(bo.getUserId() != null, SysUserLoginCompany::getUserId, bo.getUserId());
        lqw.eq(bo.getSubstationId() != null, SysUserLoginCompany::getSubstationId, bo.getSubstationId());
        lqw.eq(bo.getIsDeleted() != null, SysUserLoginCompany::getIsDeleted, bo.getIsDeleted());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), SysUserLoginCompany::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getCardFrontUrl()), SysUserLoginCompany::getCardFrontUrl, bo.getCardFrontUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCardBackUrl()), SysUserLoginCompany::getCardBackUrl, bo.getCardBackUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCardId()), SysUserLoginCompany::getCardId, bo.getCardId());
        lqw.eq(bo.getResignationTime() != null, SysUserLoginCompany::getResignationTime, bo.getResignationTime());
        lqw.eq(bo.getEntryTime() != null, SysUserLoginCompany::getEntryTime, bo.getEntryTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUserType()), SysUserLoginCompany::getUserType, bo.getUserType());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), SysUserLoginCompany::getCompanyName, bo.getCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyFrontUrl()), SysUserLoginCompany::getCompanyFrontUrl, bo.getCompanyFrontUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyBackUrl()), SysUserLoginCompany::getCompanyBackUrl, bo.getCompanyBackUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyAbbreviation()), SysUserLoginCompany::getCompanyAbbreviation, bo.getCompanyAbbreviation());
        lqw.eq(StringUtils.isNotBlank(bo.getSettlementType()), SysUserLoginCompany::getSettlementType, bo.getSettlementType());
        lqw.eq(bo.getProvince() != null, SysUserLoginCompany::getProvince, bo.getProvince());
        lqw.eq(bo.getCity() != null, SysUserLoginCompany::getCity, bo.getCity());
        lqw.eq(bo.getDistrict() != null, SysUserLoginCompany::getDistrict, bo.getDistrict());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), SysUserLoginCompany::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getBillingUSCI()), SysUserLoginCompany::getBillingUSCI, bo.getBillingUSCI());
        lqw.eq(StringUtils.isNotBlank(bo.getBillingOpeningBank()), SysUserLoginCompany::getBillingOpeningBank, bo.getBillingOpeningBank());
        lqw.eq(StringUtils.isNotBlank(bo.getBillingAccountNumber()), SysUserLoginCompany::getBillingAccountNumber, bo.getBillingAccountNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getBillingTel()), SysUserLoginCompany::getBillingTel, bo.getBillingTel());
        lqw.orderByDesc(SysUserLoginCompany::getCreateTime);
        return lqw;
    }

    /**
     * 新增公司信息
     */
    @Override
    public Boolean insertByBo(SysUserLoginCompanyBo bo) {
        SysUserLoginCompany add = BeanUtil.toBean(bo, SysUserLoginCompany.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setDriverId(add.getDriverId());
        }
        return flag;
    }

    /**
     * 修改公司信息
     */
    @Override
    public Boolean updateByBo(SysUserLoginCompanyBo bo) {
        SysUserLoginCompany update = BeanUtil.toBean(bo, SysUserLoginCompany.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserLoginCompany entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除公司信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public String checkRepeatInfo(AdminSysUserLoginCompanyBo bo) {
        SysUserLoginCompany sysUserLoginCompany = baseMapper.selectOne(new LambdaQueryWrapper<SysUserLoginCompany>()
            .ne(bo.getDriverId() != null, SysUserLoginCompany::getDriverId, bo.getDriverId())
            .and((i) -> {
                i.eq(SysUserLoginCompany::getCompanyName, bo.getCompanyName())
                    .or()
                    .eq(SysUserLoginCompany::getCompanyAbbreviation, bo.getCompanyAbbreviation())
                    .or()
                    .eq(SysUserLoginCompany::getTel, bo.getTel());
            })
        );

        if (sysUserLoginCompany != null) {
            if (sysUserLoginCompany.getCompanyName().equals(bo.getCompanyName())) {
                return "公司名称已经存在，不能重复";
            }

            if (sysUserLoginCompany.getCompanyAbbreviation().equals(bo.getCompanyAbbreviation())) {
                return "公司简称已经存在，不能重复";
            }

            if (sysUserLoginCompany.getTel().equals(bo.getTel())) {
                return "手机号已经存在，不能重复";
            }
        }

        return "";
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean insertByAdminBo(AdminSysUserLoginCompanyBo bo) {
        SysUserLoginCompany sysUserLoginCompany = BeanUtil.toBean(bo, SysUserLoginCompany.class);
        validEntityBeforeSave(sysUserLoginCompany);

        // 检查用户是否存在
        SysUser sysUser = sysUserMapper.selectUserByPhonenumber(sysUserLoginCompany.getTel());

        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setUserName(sysUserLoginCompany.getTel());
            sysUser.setNickName(sysUserLoginCompany.getCompanyName());
            sysUser.setPhonenumber(sysUserLoginCompany.getTel());
            sysUser.setStatus(UserStatus.OK.getCode());
            sysUser.setUserType(UserType.SYS_USER.getUserType());
            sysUser.setPassword(null);
            sysUser.setCreateBy(LoginHelper.getUsername());
            sysUser.setCreateTime(DateUtils.getNowDate());
            sysUser.setDelFlag("0");

            int insert = sysUserMapper.insert(sysUser);
            if (insert == 0) {
                log.info("公司用户：{} 注册失败", sysUserLoginCompany.getTel());
                throw new UserException("公司用户注册失败");

            }

            sysUserLoginCompany.setRelevanceUserId(sysUser.getUserId());
        }

        sysUserLoginCompany.setRelevanceUserId(sysUser.getUserId());
        sysUserLoginCompany.setUserType(UserType.SYS_USER.getUserType());
        sysUserLoginCompany.setIsDeleted(0);

        int insert = baseMapper.insert(sysUserLoginCompany);
        if (insert == 0) {
            throw new ServiceException("公司创建失败");
        }

        return true;
    }

    @Override
    public Boolean updateByAdminBo(AdminSysUserLoginCompanyBo bo) {
        SysUserLoginCompany sysUserLoginCompany = BeanUtil.toBean(bo, SysUserLoginCompany.class);
        validEntityBeforeSave(sysUserLoginCompany);

        int update = baseMapper.updateById(sysUserLoginCompany);
        if (update == 0) {
            throw new ServiceException("公司修改失败");
        }

        return true;
    }

}
